<template>
  <div class="app-container">
    <!-- 搜索 -->
    <page-search
      ref="searchRef"
      :search-config="searchConfig"
      @query-click="handleQueryClick"
      @reset-click="handleResetClick"
    />

    <!-- 列表 -->
    <page-content
      ref="contentRef"
      :content-config="contentConfig"
      @add-click="handleAddClick"
      @edit-click="handleEditClick"
      @export-click="handleExportClick"
      @toolbar-click="handleToolbarClick"
      @operat-click="handleOperatClick"
    >
      <template #status="scope">
        <el-tag :type="scope.row[scope.prop] == 1 ? 'success' : 'info'">
          {{ scope.row[scope.prop] == 1 ? "启用" : "禁用" }}
        </el-tag>
      </template>
      <template #userType="scope">
        {{ proxy.$getOptionLabel(scope.row[scope.prop], userTypeList) }}
      </template>
      <template #sex="scope">
        {{ proxy.$getOptionLabel(scope.row[scope.prop], sexList) }}
      </template>
      <template #time="scope">
        {{ getTime(scope.row[scope.prop]) }}
      </template>
      <template #action="scope">
        <el-button type="primary" size="small" @click="handleEdit(scope.row)">
          编辑
        </el-button>
        <el-button type="primary" size="small" @click="handleDelete(scope.row)">
          删除
        </el-button>
        <el-button type="primary" size="small" @click="handleConfig(scope.row)">
          AEG参数配置
        </el-button>
      </template>
    </page-content>

    <!-- 新增 -->
    <page-modal
      ref="addModalRef"
      :modal-config="addModalConfig"
      @submit-click="handleSubmitClick"
    />

    <!-- 编辑 -->
    <page-modal
      ref="editModalRef"
      :modal-config="editModalConfig"
      @submit-click="handleSubmitClick"
    />
    <el-dialog
      v-model="dialogVisible"
      title="AEG参数配置"
      width="800"
      :before-close="handleClose"
    >
      <el-form
        class="base-form"
        ref="baseFormRef"
        :model="baseForm"
        auto-complete="on"
      >
        <el-table
          ref="table-input"
          class="table"
          border
          :header-cell-style="{
            background: '#F5F5F5',
            color: '#333',
          }"
          stripe
          height="500"
          highlight-current-row
          :data="baseForm.demoList"
        >
          <el-table-column label="所属组" show-overflow-tooltip>
            <template v-slot:header>
              <div><span class="star">*</span>所属组</div>
            </template>
            <template v-slot="scope">
              <el-form-item
                :prop="'demoList.' + scope.$index + '.parameterGroup'"
                :rules="rules.parameterGroup"
                class="all"
              >
                <el-select
                  v-model="scope.row.parameterGroup"
                  filterable
                  placeholder="请选择"
                  collapse-tags
                  clearable
                  :disabled="scope.row.id != ''"
                  @focus="
                    baseFormRef.clearValidate(
                      `demoList.${scope.$index}.parameterGroup`
                    )
                  "
                >
                  <el-option
                    v-for="item in state.configList"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="参数名" show-overflow-tooltip>
            <template #header="scope">
              <div><span class="star">*</span>参数名</div>
            </template>
            <template #default="scope">
              <el-form-item
                :prop="'demoList.' + scope.$index + '.parameterName'"
                class="all"
                :rules="rules.parameterName"
              >
                <el-input
                  v-model.trim="scope.row.parameterName"
                  placeholder="请输入"
                  @focus="
                    baseFormRef.clearValidate(
                      `demoList.${scope.$index}.parameterName`
                    )
                  "
                  clearable
                ></el-input>
                <!-- <template v-slot:error>--</template> -->
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="参数值" show-overflow-tooltip>
            <template v-slot:header>
              <div><span class="star">*</span>参数值</div>
            </template>
            <template v-slot="scope">
              <el-form-item
                :prop="'demoList.' + scope.$index + '.parameterValue'"
                :rules="rules.parameterValue"
                class="all"
              >
                <el-input
                  v-model.trim="scope.row.parameterValue"
                  placeholder="请输入"
                  clearable
                  @focus="
                    baseFormRef.clearValidate(
                      `demoList.${scope.$index}.parameterValue`
                    )
                  "
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="参数描述" show-overflow-tooltip>
            <template v-slot="scope">
              <el-form-item
                :prop="'demoList.' + scope.$index + '.remark'"
                :rules="rules.remark"
                class="all"
              >
                <el-input
                  v-model.trim="scope.row.remark"
                  placeholder="请输入"
                  clearable
                  @focus="
                    baseFormRef.clearValidate(`demoList.${scope.$index}.remark`)
                  "
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template v-slot="scope">
              <el-button size="small" @click="deleteDomain(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-form-item style="margin-top: 10px; margin-bottom: 0">
          <el-button @click="addDomain">新增配置项</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="submitConfigForm">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import searchConfig from "./config/search";
import contentConfig from "./config/content";
import addModalConfig from "./config/add";
import editModalConfig from "./config/edit";
import usePage from "@/hooks/usePage";
import { useAppStore, useUserStore } from "@/store";
import type { IOperatData, IObject } from "@/hooks/usePage";
import { getCurrentInstance } from "vue";
import { dayjs } from "element-plus";
import {
  getAreaList,
  getVPNList,
  ComputerConfigList,
  addEdgeParamsConfig,
} from "@/api/keeplive/machineRoom/index";
import { delComputer } from "@/api/keeplive/machineRoom/index";
const { proxy }: any = getCurrentInstance();
const {
  searchRef,
  contentRef,
  addModalRef,
  editModalRef,
  handleQueryClick,
  handleResetClick,
  handleAddClick,
  // handleEditClick,
  handleSubmitClick,
  handleExportClick,
} = usePage();
const appStore = useAppStore();
const userStore = useUserStore();
const optionList = computed(() => appStore.optionList);
const sexList = computed(() => appStore.sexList);
import { ref, reactive } from "vue";
import { ElMessageBox } from "element-plus";
const baseFormRef = ref(ElForm); // 用户表单
const dialogVisible = ref(false);
const tcrcode = ref<number | string>("");
const handleClose = (done: () => void) => {
  ElMessageBox.confirm("Are you sure to close this dialog?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};
// type IObject = Record<string, any>;
const baseForm = reactive<IObject>({
  demoList: [
    {
      id: 145,
      parameterGroup: "JFSD.BYWG",
      parameterName: "123",
      parameterValue: "456",
      delFlag: "0",
      remark: "RADIUS服务配置",
    },
  ],
});
const rules = reactive<IObject>({
  parameterGroup: [
    {
      required: true,
      message: "请选择所属组",
      trigger: "change",
    },
  ],
  parameterName: [
    { required: true, message: "参数名不能为空", trigger: "blur" },
  ],
  parameterValue: [
    { required: true, message: "参数值不能为空", trigger: "blur" },
  ],
  // remark: [
  //   { required: true, message: "请输入参数描述", trigger: "blur" },
  // ],
});
const state = reactive({
  configList: <IObject[]>[
    {
      value: "JFSD.BYWG",
      label: "RADIUS服务配置",
    },
    {
      value: "JFSD.BYWG.AIOT",
      label: "AIOT参数配置",
    },
    {
      value: "JFSD.BYWG.YWJK",
      label: "运监参数配置",
    },
    {
      value: "JFSD.BYWG.RH",
      label: "融合配置",
    },
    {
      value: "JFSD.BYWG.COMM",
      label: "其他配置",
    },
  ],
  catchList: <IObject[]>[],
});
// const configList = reactive<IObject[]>([
//   {
//     value: "JFSD.BYWG",
//     label: "RADIUS服务配置",
//   },
//   {
//     value: "JFSD.BYWG.AIOT",
//     label: "AIOT参数配置",
//   },
//   {
//     value: "JFSD.BYWG.YWJK",
//     label: "运监参数配置",
//   },
//   {
//     value: "JFSD.BYWG.RH",
//     label: "融合配置",
//   },
//   {
//     value: "JFSD.BYWG.COMM",
//     label: "其他配置",
//   },
// ]);
function addDomain() {
  //先隐藏delFlag为1的数据， 最后过滤掉数组中id为空且delFlag为'1'的数据
  //不隐藏直接删除，最后添加数据库数组中已经删掉的配置项，把delFlag修改为1
  baseForm.demoList.push({
    id: "",
    parameterGroup: "",
    parameterName: "",
    parameterValue: "",
    delFlag: "0",
    remark: "",
  });
}
// const userTypeList = reactive({
//   parentId: [{ required: true, message: "请选择顶级菜单", trigger: "blur" }],
//   name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
//   type: [{ required: true, message: "请选择菜单类型", trigger: "blur" }],
//   path: [{ required: true, message: "请输入路由路径", trigger: "blur" }],

//   component: [{ required: true, message: "请输入组件路径", trigger: "blur" }],
//   visible: [{ required: true, message: "请输入路由路径", trigger: "blur" }],
// });
const userTypeList = reactive([
  { label: "普通用户", value: "1" },
  { label: "协同操作人", value: "2" },
  { label: "管理员", value: "3" },
]);
function handleConfig(data: IObject) {
  console.log(data);
  dialogVisible.value = true;
  getConfigList(data);
}
function getConfigList(val: IObject) {
  const { tcrcode: code, tcrname } = val;
  if (code) {
    tcrcode.value = code;
    // this.tcrcode = tcrcode;
    // this.tcrname = tcrname;
    state.configList = state.configList.map((item) => {
      // 匹配点以外的所有正则
      const value = item.value.replace(/[^\.]*\./, `${code}.`);
      return {
        label: item.label,
        value: value,
      };
    });
    ComputerConfigList({
      tcrcode: code,
    }).then((res) => {
      const { data } = res;
      if (data.code == 200) {
        const { edgeParamsConfigsList } = data.data;
        baseForm.demoList = edgeParamsConfigsList;
        state.catchList = edgeParamsConfigsList.map((i: IObject) => ({ ...i }));
      } else {
        ElMessage({
          message: data.msg,
          type: "error",
        });
      }
    });
  } else {
    // this.$message.error("机房编码不存在！");
  }
}
function deleteDomain(item: object) {
  ElMessageBox.confirm("此操作将删除参数配置项, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    var index = baseForm.demoList.indexOf(item);
    if (index !== -1) {
      baseForm.demoList.splice(index, 1);
    }
  });
}
function submitConfigForm(params: IObject) {
  baseFormRef.value.validate((valid: Boolean) => {
    if (valid) {
      // this.$confirm("您确定【提交】？", "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning",
      // }).then(() => {

      // });
      const { demoList } = baseForm;
      const { catchList } = state;
      console.log("校验通过", demoList, catchList);
      // 利用缓存增加数组参数数据库有的只允许物理删除
      const arr = catchList.map((item) => {
        const index = demoList.findIndex((i: IObject) => i.id == item.id);
        return index == -1 ? { ...item, delFlag: "2" } : "";
      });
      let params = {
        edgeParamsConfigsList: [...demoList, ...arr.filter((i) => i)],
        tcrcode: tcrcode.value,
      };
      if (params.edgeParamsConfigsList.length == 0) {
        ElMessage({
          message: "请添加AEG参数配置项！",
          type: "error",
        });
        return;
      }
      addEdgeParamsConfig(params).then((res) => {
        const { data } = res;
        if (data.code == 200) {
          ElMessage({
            message: data.msg,
            type: "success",
          });
          // this.$message.success(data.msg);
          dialogVisible.value = false;
          contentRef.value?.fetchPageData({}, true);
          // this.refresh();
        } else {
          ElMessage({
            message: data.msg,
            type: "error",
          });
        }
      });
    }
  });
}
function getareaList(data: string) {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await getAreaList();
      searchConfig.formItems.forEach((i) => {
        if (
          i.prop == "tcraddress" &&
          i.type == "select" &&
          Array.isArray(i.options) &&
          i.options.length == 0
        ) {
          const { data } = res;
          console.log(res, data);
          i.options = data.rows.map((i) => {
            // console.log(i.areaname, i.areaid);
            return {
              value: i.areaid,
              label: i.areaname,
            };
          });
        }
      });
      addModalConfig.formItems.forEach((i) => {
        if (
          i.prop == "tcraddress" &&
          i.type == "select" &&
          Array.isArray(i.options) &&
          i.options.length == 0
        ) {
          const { data } = res;
          i.options = data.rows.map((i) => {
            // console.log(i.areaname, i.areaid);
            return {
              value: i.areaid,
              label: i.areaname,
            };
          });
        }
      });
      editModalConfig.formItems.forEach((i) => {
        if (
          i.prop == "tcraddress" &&
          i.type == "select" &&
          Array.isArray(i.options) &&
          i.options.length == 0
        ) {
          const { data } = res;
          i.options = data.rows.map((i) => {
            // console.log(i.areaname, i.areaid);
            return {
              value: i.areaid,
              label: i.areaname,
            };
          });
        }
      });
      resolve(res);
    } catch (error) {
      reject(error);
    }
  });
}
async function getvpnList(data: string) {
  try {
    const res = await getVPNList();
    searchConfig.formItems.forEach((i) => {
      if (
        i.prop == "deviceCode" &&
        i.type == "select" &&
        Array.isArray(i.options) &&
        i.options.length == 0
      ) {
        const { data } = res;
        console.log(res, data);
        i.options = data.rows.map((i) => {
          return {
            value: i,
            label: i,
          };
        });
      }
    });
  } catch (err) {}
}

getareaList("");
getvpnList("");
function handleLogin() {
  let params = {
    username: "string",
    password: "string",
  };
  userStore.login(params).then((res) => {
    console.log(res);
  });
}
handleLogin();
function getTime(params: string) {
  return dayjs(params).format("YYYY-MM-DD");
}

// 编辑
function handleEditClick(row: IObject) {}
// function handleEditClick(row: IObject) {
//   // 模拟根据id获取数据进行填充
//   const idMap: IObject = {
//     2: {
//       id: 2,
//       username: "admin",
//       nickname: "系统管理员",
//       mobile: "17621210366",
//       gender: 1,
//       avatar:
//         "https://oss.youlai.tech/youlai-boot/2023/05/16/811270ef31f548af9cffc026dfc3777b.gif",
//       email: "",
//       status: 1,
//       deptId: 1,
//       roleIds: [2],
//     },
//     3: {
//       id: 3,
//       username: "test",
//       nickname: "测试小用户",
//       mobile: "17621210366",
//       gender: 1,
//       avatar:
//         "https://oss.youlai.tech/youlai-boot/2023/05/16/811270ef31f548af9cffc026dfc3777b.gif",
//       email: "youlaitech@163.com",
//       status: 1,
//       deptId: 3,
//       roleIds: [3],
//     },
//   };
//   editModalRef.value?.setModalVisible(idMap[row.id]);
// }
function handleEdit(row: IObject) {
  const obj = {
    ...row,
    tcraddress: row.areaIds,
  };
  // row.tcraddress = row.areaIds;
  editModalRef.value?.setModalVisible(obj);
}
function handleDelete(row: IObject) {
  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async function () {
    try {
      let params = {
        ids: row.id,
        delFlag: 2,
      };
      const res = await delComputer(params);
      handleSubmitClick();
      console.log(res);
    } catch (error) {
      console.log(error);
    }
  });
}

// 其他工具栏
function handleToolbarClick(name: string) {
  console.log(name);
  if (name === "import") {
    ElMessage.success("点击了导入按钮");
  }
}
// 其他操作列
function handleOperatClick(data: IOperatData) {
  console.log(data);
  // 重置密码
  if (data.name === "reset_pwd") {
    ElMessageBox.prompt(
      "请输入用户「" + data.row.username + "」的新密码",
      "重置密码",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }
    ).then(({ value }) => {
      if (!value) {
        ElMessage.warning("请输入新密码");
        return false;
      }
      // 发送网络请求
      ElMessage.success("密码重置成功，新密码是：" + value);
    });
  }
}
</script>
